package com.hc.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.hc.comm.CommData;

public class DownFileUtil {
	
	
	
	public static void downFile(String query, HttpServletResponse resp) {

		try {
	
			File file = new File(CommData.excelTempFilePath);

			String[] files = file.list();
			boolean state = false;
			for (String fileName : files) {

				if (fileName.indexOf(query) != -1) {

					file = new File(file.getPath() + "/" + fileName);

					if (file.exists()) {
						state = true;
						resp.setCharacterEncoding("utf-8");
			
						resp.setHeader(
								"Content-Disposition",
								"attachment;filename="
										+ URLEncoder.encode(file.getName(),
												"UTF-8"));
						resp.setHeader("Content-length", ""+file.length());
						FileInputStream fis = new FileInputStream(file);
						ServletOutputStream out = resp.getOutputStream();
						byte[] bytes = new byte[1024*2];

						int len = -1;

						while ((len = fis.read(bytes)) != -1) {

							out.write(bytes);
							out.flush();
						}

						if (fis != null) {
							try {

								fis.close();
							} finally {

								out.close();
							}

						}

					}

				}

			}

			if (!state) {

				outMsg("文件不存在，请与管理员联系", resp);
			}

		} catch (Exception e) {

			outMsg("传输文件出错 ， 请与管理员联系 ", resp);

		}
	}
	
	public static void outMsg(String msg, HttpServletResponse resp) {
		resp.setCharacterEncoding("utf-8");
		resp.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter w;
		try {
			w = resp.getWriter();
			w.write(msg);
		} catch (IOException e) {

			e.printStackTrace();
		}

	}
	
}
